﻿$(function () {
    $.kish.carSearch = {};
    $.extend($.kish.carSearch, {

        //********************************//
        WithTotal: null,
        //set basid details
        initializing: function () {
            $.kish.carSearch.SetBrandDrp();
            $.kish.carSearch.SetColorDrp();
            $.kish.carSearch.SetStatusDrp();
            $.kish.carSearch.CarSearch(0, 20, false);

            $(".carSearchSubmit").click(function () {
                $.kish.carSearch.CarSearch(0, 20, true);
            });

            $('.brandDrp').change(function () {
                $('.modelDrp').html('');
                var brandID = $(this).val();
                if (brandID != 0)
                    $.kish.carSearch.SetModelDrp(brandID);
            });
        },

        //********************************//
        SetBrandDrp: function () {
            var brandDrp = $('.brandDrp');
            var url = '../../KishCar/Services/CarAnn.svc/GetAllBrands';
            var data = '';
            var topOption = '---';
            $.Jahanutility.fillDrp(brandDrp, url, data, topOption);
        },


        //**********************************************************
        SetModelDrp: function (ID, ModelID) {
            var brandDrp = $('.modelDrp');
            var url = '../../KishCar/Services/CarAnn.svc/GetModel';
            var data = JSON.stringify({ modelID: ID });
            var topOption = '---';
            $.Jahanutility.fillDrp(brandDrp, url, data, topOption, ModelID);
        },

        //        setModel: function (ModelID) {
        //            $(".modelDrp").val(ModelID);
        //        },


        //**********************************************************
        SetColorDrp: function (ID) {
            var brandDrp = $('.colorDrp');
            var url = '../../KishCar/Services/CarAnn.svc/GetColor';
            var data = '';
            var topOption = '---';
            $.Jahanutility.fillDrp(brandDrp, url, data, topOption);
        },

        //**********************************************************
        SetStatusDrp: function () {
            var brandDrp = $('.stateDrp');
            var url = '../../KishCar/Services/CarAnn.svc/GetAllStatus';
            var data = '';
            var topOption = '---';
            $.Jahanutility.fillDrp(brandDrp, url, data, topOption);
        },

        //**********************************************************
        CarSearch: function (start, end, withtotal) {
            $('.isNumeric').each(function () {
                $(this).triggerHandler("focusout");
            });

            $('#submit').before('<img src="../../images/ajax-loader.gif" class="loader" />')

            var SerachCarDTO = {};

            if ($.trim($(".priceFromTxt").val()) != '') {
                SerachCarDTO.PriceMin = $.trim($(".priceFromTxt").val());
                SerachCarDTO.PriceMin = Number(SerachCarDTO.PriceMin.replace(/[^0-9\.]+/g, ""));
            }
            else {
                SerachCarDTO.PriceMin = null;
            }

            if ($.trim($(".priceToTxt").val()) != '') {
                SerachCarDTO.PriceMax = $.trim($(".priceToTxt").val());
                SerachCarDTO.PriceMax = Number(SerachCarDTO.PriceMax.replace(/[^0-9\.]+/g, ""));
            }
            else {
                SerachCarDTO.PriceMax = null;
            }

            SerachCarDTO.ProductYearMin = parseInt($.trim($(".yearFromTxt").val()), 10);
            SerachCarDTO.ProductYearMax = parseInt($.trim($(".yearToTxt").val()), 10);

            SerachCarDTO.TraveledDistance_Min = parseInt($(".usageFromTxt").val(), 10);
            SerachCarDTO.TraveledDistance_Max = parseInt($(".usageToTxt").val(), 10);

            if ($(".colorDrp").val() != 0) {
                SerachCarDTO.ColorID = parseInt($(".colorDrp").val(), 10);
            }
            else {
                SerachCarDTO.ColorID = null;
            }
            if ($(".modelDrp").val() != 0) {
                SerachCarDTO.ModelID = parseInt($(".modelDrp").val(), 10);
            }
            else {
                SerachCarDTO.ModelID = null;
            }

            if ($(".stateDrp").val() != 0) {
                SerachCarDTO.StatusID = parseInt($(".stateDrp").val(), 10);
            }
            else {
                SerachCarDTO.StatusID = null;
            }

            //null for search field means query comes with default filter by Taarefe
            var searchField = null;
            if ($('.sortFieldDrp').val() != 0)
                searchField = $('.sortFieldDrp').val();

            var isAscend = $('.IsAscend').val();

            $('#submit').attr('disabled', 'disabled');
            $.ajax({
                'type': 'POST',
                'url': '../../KishCar/Services/CarAnn.svc/SerachCar',
                'data': JSON.stringify({ Condition: SerachCarDTO, Start: start, End: end, withTotal: withtotal, SearchField: searchField, IsAscend: isAscend }),
                'contentType': 'application/json; charset=utf-8',
                'dataType': 'json',
                'success': function (data) {

                    if (data['d'] == null || data['d'].length == 0) {
                        $.kish.message.getErrorMessage("15");
                        $('.searchResults').html('');
                    }
                    else {
                        $('.searchResults').html('');
                        var Cars = data['d'].Data;
                        for (var i = 0; i < Cars.length; i++) {
                            var price = $.trim(Cars[i].Price);
                            var path = '../Images/carNoPhoto.gif';
                            if (Cars[i].CarImages[0] != null) {
                                var relatedPath = (Cars[i].CarImages[0].Path);
                                path = '../' + relatedPath.replace('~', '..');
                            }
                            var x = '<div class="three columns isotope-item ">' +
                                        '<a class="portfolio-item isotope " href="CarDetails.aspx?ID=' + Cars[i].ID + '">' +
                                            '<figure>' +
                                            '<div class="crop">' +
                                                '<img alt="" src="' + path + '">' +
                                            '</div>' +
						                        '<figcaption class="item-description">' +
							                        '<h5>' + Cars[i].Model.Code + ' ' + Cars[i].Model.Brand.Code + '</h5>' +
                            //							                        '<span>' + $.trim(data['d'][i].Color.Code) + '</span>' + ' ' +
                            //                                                    '<span>' + $.trim(data['d'][i].ProductYear) + '</span>' +
                                                  '<span >تومان </span>' + '<span>' + price + '</span>' +
                                                 '</figcaption>' +
					                       '</figure>' +
                                        '</a>' +
                                    '</div>';
                            $('.searchResults').append(x);
                        };
                        if (withtotal && data['d'].TotalCount && data['d'].TotalCount > 0 && data['d'].TotalCount != null) {
                            $.kish.carSearch.WithTotal = data['d'].TotalCount;
                            $.kish.carSearch.SetPaging();
                        }
                    };

                    $('#message').slideDown();
                    $('img.loader').fadeOut('slow', function () { $(this).remove() });
                    $('#submit').removeAttr('disabled', 'disabled');
                },
                'error': function (error) {
                    $('#submit').removeAttr('disabled');
                    $('img.loader').fadeOut('slow', function () { $(this).remove() });
                }
            });
        },
        SetPaging: function () {
            var withTotal = $.kish.carSearch.WithTotal;
            var PageCount = Math.ceil(withTotal / 20);
            var paging = '';
            for (var i = 0; i < PageCount; i++) {
                var PageItem = '<span class="pagingItem">' + (i + 1).toString() + '</span>';
                paging = paging + PageItem;
            }            
            $('.PagingDiv').text('');
            $('.PagingDiv').append(paging);
            $('.PagingDiv').append('<span class="totalCount"> کل موارد یافت شده : ' + withTotal + '</span>');
            $(".pagingItem").click(function () {
                var pageIndex = $(this).text();
                $.kish.carSearch.CarSearch((pageIndex - 1) * 20, pageIndex * 20, false);
            });
        }

    });
    $.kish.carSearch.initializing();
});



